package com.fisicaapp;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;

/* exportar xls */

import java.io.IOException;
import jxl.write.WriteException;



public class SampleChart extends Activity {
    private GraphicalView chart1;
    private GraphicalView chart2;
    private XYMultipleSeriesDataset dataset1 = new XYMultipleSeriesDataset();
    private XYMultipleSeriesRenderer renderer1 = new XYMultipleSeriesRenderer();
    private XYSeries series1;
    private XYSeriesRenderer seriesRenderer1;
    private XYMultipleSeriesDataset dataset2 = new XYMultipleSeriesDataset();
    private XYMultipleSeriesRenderer renderer2 = new XYMultipleSeriesRenderer();
    private XYSeries series2;
    private XYSeriesRenderer seriesRenderer2;
    private String nombre_archivo="";
    
    private double [] ejeT;
    private double [] ejeY;
    private double [] ejeX;
    private String [] cap; //caption para el grafico y excel
    private String data;
    private AlertDialog.Builder txtInfo; // creamos variable de mensaje de alerta
    
    private double maxVal(double [] time){
    	double max=0;
    	for (int i=0;i<time.length;i++){
    		if (max<time[i]) max = time[i];
    	}
    	return max;
    }
    private double minVal(double [] v){
    	double min=0;
    	for (int i=0;i<v.length;i++){
    		if (min > v[i]) min = v[i];
    	}
    	return min;
    }
    
    
    private void initChart(int caso) {
    	
    	switch(caso){
    	case 1:
    		series1 = new XYSeries(cap[1]);
    		series1.setTitle(cap[1]);    		
            dataset1.addSeries(series1);
            seriesRenderer1 = new XYSeriesRenderer();
            //seriesRenderer1.setDisplayChartValues(true);
            seriesRenderer1.setPointStyle(PointStyle.CIRCLE);
            seriesRenderer1.setFillPoints(true);
            seriesRenderer1.setDisplayChartValuesDistance(10);
            seriesRenderer1.setColor(Color.BLUE);
            
            renderer1.addSeriesRenderer(seriesRenderer1);            
            renderer1.setPanEnabled(true, true);        
            renderer1.setInScroll(true);
            renderer1.setChartTitle(cap[3]);
            renderer1.setXAxisMax(maxVal(ejeT));
            renderer1.setXAxisMin(0);
            renderer1.setYAxisMax(maxVal(ejeX)+ 2);
            renderer1.setYAxisMin(minVal(ejeX) - 2);
            renderer1.setXTitle(cap[6]);
            renderer1.setYTitle(cap[5]);
            renderer1.setShowGrid(true);
            renderer1.setGridColor(Color.BLACK);
            renderer1.setZoomButtonsVisible(true);
    		break;
    	case 2:
    		     	
        	 series2 = new XYSeries(cap[2]);
        	 series2.setTitle(cap[2]);
             dataset2.addSeries(series2);             
             seriesRenderer2 = new XYSeriesRenderer();
             //seriesRenderer2.setDisplayChartValues(true);
             seriesRenderer2.setPointStyle(PointStyle.CIRCLE);
             seriesRenderer2.setFillPoints(true);
             seriesRenderer2.setDisplayChartValuesDistance(10);      
             
             seriesRenderer2.setColor(Color.RED);
             renderer2.addSeriesRenderer(seriesRenderer2);
             
             renderer2.setInScroll(true);
             renderer2.setChartTitle(cap[4]);
             renderer2.setXAxisMax(maxVal(ejeT));
             renderer2.setXAxisMin(0);
             renderer2.setYAxisMax(maxVal(ejeY)+ 2);
             renderer2.setYAxisMin(minVal(ejeY) - 2);
             renderer2.setXTitle(cap[6]);
             renderer2.setYTitle(cap[5]);
             renderer2.setShowGrid(true);
             renderer2.setGridColor(Color.BLACK);             
             renderer2.setPanEnabled(true, true);
             renderer2.setZoomButtonsVisible(true);
             
    		break;
    	}
        
    }

    private void addSampleData(double[] ex, double[] ey, int caso) {    	
    	switch(caso){
    	case 1:
    		for (int i=0;i<ex.length;i++){    			
        		series1.add(ex[i],ey[i]);        		
    		}
    		break;
    	case 2:
    		 for (int i=0;i<ex.length;i++){        		
         		series2.add(ex[i], ey[i]);
    		 }    		 
    		break;
    	}
        
        
    }
 
	
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.xy_chart);
        txtInfo = new AlertDialog.Builder(this); 
        txtInfo.setTitle("Mensaje"); 
        Bundle extras = getIntent().getExtras();
       
        data = extras.getString("yourkey_data");
        ejeX = extras.getDoubleArray("yourkey1");
        ejeY = extras.getDoubleArray("yourkey2");
        if (data.equals("0")){
        	cap = new String[]{"Tiempo","Aceleracion X", "Aceleracion Y", 
        			"Aceleracion X vs Tiempo","Aceleracion Y vs Tiempo", 
        			"Aceleracion [m/s2]","Tiempo [s]"};
        	//defino tiempos equidistantes (para 5 seg de muestreo)
        	double dt = (double)5/ejeX.length;
            double c=0;
            ejeT = new double[ejeX.length];
            for (int j=0;j<ejeX.length;j++){        	      	
            	ejeT[j] = c;
            	c += dt;        	
            }
        	
            
        }else if(data.equals("1")){
        	cap = new String[]{"Tiempo","Posicion X", "Posicion Y", 
        			"Posicion X vs Tiempo","Posicion Y vs Tiempo", 
        			"Posicion [m]","Tiempo [s]"};
        	 ejeT = extras.getDoubleArray("yourkeyt");
             
           
        }
        else if(data.equals("2")){
        	cap = new String[]{"Tiempo","Velocidad X", "Velocidad Y", 
        			"Velocidad X vs Tiempo","Velocidad Y vs Tiempo", 
        			"Velocidad [m/s]","Tiempo [s]"};
        	 ejeT = extras.getDoubleArray("yourkeyt");
             
           
        }
        
       
      
    }

    protected void onResume() {
        super.onResume();
        LinearLayout layout1 = (LinearLayout) findViewById(R.id.chart1);
        LinearLayout layout2 = (LinearLayout) findViewById(R.id.chart2);
        if (chart1 == null) {
            initChart(1);
            addSampleData(ejeT, ejeX,1);  
           
           	chart1 = ChartFactory.getLineChartView(this, dataset1, renderer1);
           
           
            layout1.addView(chart1);
            
        } else {
            chart1.repaint();
        }
        if (chart2 == null) {
            initChart(2);
            addSampleData(ejeT,ejeY,2);
           
           	chart2 = ChartFactory.getLineChartView(this, dataset2, renderer2);
           
            layout2.addView(chart2);
            
        } else {
            chart2.repaint();
        }
        
     
        
    }
    
    public void crearAlert(){
	    AlertDialog.Builder alert = new AlertDialog.Builder(SampleChart.this);
	
	    alert.setTitle("Nombre Archivo");
	    LayoutInflater inflater = this.getLayoutInflater();
	    final View v = inflater.inflate(R.layout.input_nombrearchivo, null);    
	    alert.setView(v);
	   
	    alert.setPositiveButton("Ingresar", new DialogInterface.OnClickListener() {
	        public void onClick(DialogInterface dialog, int whichButton) {
	
	            final EditText text1 = (EditText) v.findViewById(R.id.editTextFileName);        
	           
	            Editable val1 = text1.getText();            
	            nombre_archivo = val1.toString();            
	            if(nombre_archivo.equals("")){
	          	  	crearAlert();
		          	txtInfo.setPositiveButton("Cerrar", null);				
					txtInfo.setMessage("No ingreso un nombre.");
					txtInfo.show();
	            }else{
	            	try {       		
	    				WriteExcel test = new WriteExcel(ejeT,ejeX,ejeY,cap);
	    				test.setOutputFile("/sdcard/"+nombre_archivo+".xls");
	    				test.write();				
	    				txtInfo.setPositiveButton("Cerrar", null);				
	    				txtInfo.setMessage("Archivo exportado exitosamente.");
	    				txtInfo.show();
	    				
	    			} catch (WriteException e) {
	    				// TODO Auto-generated catch block
	    				txtInfo.setPositiveButton("Cerrar", null);
	    				txtInfo.setMessage("Error al exportar.");
	    		    	txtInfo.show();
	    				
	    				e.printStackTrace();
	    			} catch (IOException e) {
	    				// TODO Auto-generated catch block
	    				txtInfo.setPositiveButton("Cerrar", null);
	    		    	txtInfo.setMessage("Error al exportar.");
	    		    	txtInfo.show();
	    				
	    				e.printStackTrace();
	    			}
	            }
	          
	            
	        }
	    });
	    alert.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
	        public void onClick(DialogInterface dialog, int whichButton) {
	               // botonGrafico.setVisibility(Button.INVISIBLE);
	               
	        }
	    });
	    alert.show();
	}
    
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_chart, menu);
        return true;
    }

    /* Items del menu */
    public boolean onOptionsItemSelected(MenuItem item) { //acciones para los elementos del menu
        switch (item.getItemId()) {
        
        case R.id.VolverXX:
        	finish();
        
        case R.id.ExportarXX:
        	crearAlert();
        	
        }
        	
        	
        return true;
    }
       
}
    
    
